package com.sina.net;


import com.liwei.easyweibo.util.Util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class SinaWeiboAuthor extends Activity {
	// ΢������֤ҳ��,�滻�������ṩ��WeiboDialog ��ΪҪ������Ļ�ϴ���ֻ���Dialog ��С�������������滻��
	static final FrameLayout.LayoutParams FILL = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
			ViewGroup.LayoutParams.FILL_PARENT);
	static final int MARGIN = 4;
	static final int PADDING = 2;
	private final Weibo mWeibo = Weibo.getInstance();;
	private static String mUrl;
	private static WeiboDialogListener mListener;
	private ProgressDialog mSpinner;
	private ImageView mBtnClose;
	private WebView mWebView;
	private RelativeLayout webViewContainer;
	private RelativeLayout mContent;
	private final static String TAG = "SinaWeiboAuthor";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mSpinner = new ProgressDialog(this);
		mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mSpinner.setMessage("Loading...");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mContent = new RelativeLayout(this);
		mContent.setBackgroundColor(Color.WHITE);
		// mContent.setVerticalFadingEdgeEnabled(true);
		// mContent.requestFocus();
		// ###
		// mContent.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_repeat));
		setUpWebView();
		setUpCloseBtn();
		addContentView(mContent, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	public static void init(/* final Weibo weibo, *//* Context context, */String url, WeiboDialogListener listener) {
		// TODO ��һ����΢����֤�Ĳ����
		mUrl = url;
		mListener = listener;
	}

	private void setUpCloseBtn() {
		mBtnClose = new ImageView(this);
		mBtnClose.setClickable(true);
		mBtnClose.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mListener.onCancel();
				finish();
			}
		});

		// ### mBtnClose.setImageResource(R.drawable.sina_close_selector);
		mBtnClose.setVisibility(View.INVISIBLE);

		RelativeLayout.LayoutParams closeBtnRL = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		closeBtnRL.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		closeBtnRL.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		// ### closeBtnRL.topMargin =
		// getResources().getDimensionPixelSize(R.dimen.dialog_btn_close_right_margin);
		// ### closeBtnRL.rightMargin =
		// getResources().getDimensionPixelSize(R.dimen.dialog_btn_close_top_margin);

		webViewContainer.addView(mBtnClose, closeBtnRL);
	}

	private void setUpWebView() {
		webViewContainer = new RelativeLayout(this);
		// webViewContainer.setOrientation(LinearLayout.VERTICAL);

		// webViewContainer.addView(title, new
		// LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
		// getContext().getResources().getDimensionPixelSize(R.dimen.dialog_title_height)));

		mWebView = new WebView(this);
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new WeiboWebViewClient());
		
		// ����JS��ҳ����
		mWebView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
				return true;
			}

			@Override
			public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
				return true;
			}

			@Override
			public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
					JsPromptResult result) {
				return true;
			}

		});
		mWebView.loadUrl(mUrl);
		mWebView.setLayoutParams(FILL);
		mWebView.setVisibility(View.INVISIBLE);
		// ###
		// webViewContainer.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_repeat));
		// ###
		// mWebView.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_repeat));
		webViewContainer.addView(mWebView);

		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT);
		Resources resources = this.getResources();
		// lp.leftMargin =
		// resources.getDimensionPixelSize(R.dimen.dialog_left_margin);
		// lp.topMargin =
		// resources.getDimensionPixelSize(R.dimen.dialog_top_margin);
		// lp.rightMargin =
		// resources.getDimensionPixelSize(R.dimen.dialog_right_margin);
		// lp.bottomMargin =
		// resources.getDimensionPixelSize(R.dimen.dialog_bottom_margin);
		mContent.addView(webViewContainer, lp);
		// mContent.requestFocusFromTouch();
	}

	private class WeiboWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			Util.d(TAG, "Redirect URL: " + url);
			if (SinaWeiboAuthor.this.isFinishing()) {
				return true;
			}
			// ���̨���Ӷ�Ĭ���ض����ַ��֧�ֺ��޸�������߼�
			if (url.startsWith(mWeibo.getRedirectUrl())) {
				handleRedirectUrl(view, url);
				// WeiboDialog.this.dismiss();
				finish();
				return true;
			}
			// launch non-dialog URLs in a full browser
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			return true;
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			if (SinaWeiboAuthor.this.isFinishing()) {
				return;
			}
			mListener.onError(new DialogError(description, errorCode, failingUrl));
			finish();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d(TAG, "onPageStarted URL: " + url);
			if (SinaWeiboAuthor.this.isFinishing()) {
				return;
			}
			// google issue. shouldOverrideUrlLoading not executed
			if (url.startsWith(mWeibo.getRedirectUrl())) {
				handleRedirectUrl(view, url);
				view.stopLoading();
				finish();
				return;
			}
			super.onPageStarted(view, url, favicon);

			mSpinner.show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			Log.d(TAG, "onPageFinished URL: " + url);
			super.onPageFinished(view, url);
			if (SinaWeiboAuthor.this.isFinishing()) {
				return;
			}
			if (mSpinner.isShowing()) {
				mSpinner.dismiss();
			}

			mContent.setBackgroundColor(Color.TRANSPARENT);
			// webViewContainer.setBackgroundResource(R.drawable.sina_dialog_bg);
			// mContent.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_repeat));
			mBtnClose.setVisibility(View.VISIBLE);
			mWebView.setVisibility(View.VISIBLE);
		}

		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
			handler.proceed();
		}

	}

	private void handleRedirectUrl(WebView view, String url) {
		Bundle values = Utility.parseUrl(url);

		String error = values.getString("error");
		String error_code = values.getString("error_code");

		if (error == null && error_code == null) {
			mListener.onComplete(values);
		} else if (error.equals("access_denied")) {
			// �û�����Ȩ�������ܾ�������ݷ���Ȩ��
			mListener.onCancel();
		} else {
			mListener.onWeiboException(new WeiboException(error, Integer.parseInt(error_code)));
		}
	}
}
